package com.limh.readers.activity

import android.view.View
import butterknife.BindView
import butterknife.OnClick
import com.limh.readers.R
import com.limh.readers.bean.User
import com.limh.readers.net.CacheManager
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.SharePreferUtils
import android.app.AlertDialog
import android.os.Handler
import android.view.LayoutInflater
import android.widget.*
import com.limh.readers.comm.Comm
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.LogUtil
import org.jsoup.helper.StringUtil
import rx.schedulers.Schedulers


/**
 * Function:
 * author: limh
 * time:2017/7/21
 */
class SettingActivity : BaseActivity() {
    @BindView(R.id.txt_exit)
    lateinit var txtExit: TextView
    @BindView(R.id.line_set_user)
    lateinit var lineSetUser: LinearLayout
    @BindView(R.id.txt_email)
    lateinit var txtEmail: TextView
    @BindView(R.id.txt_cache)
    lateinit var txtCache: TextView
    @BindView(R.id.sw_image)
    lateinit var swImage: Switch

    private var user: User? = null

    val TAG = "SettingActivity"

    override fun findView() {
        setContentView(R.layout.activity_setting)
    }

    override fun initViews() {
        user = GsonUtils.str2Bean(SharePreferUtils.get(this, "user", "") as String, User::class.java)
        if (null == user) {
            txtExit.visibility = View.GONE
            lineSetUser.visibility = View.GONE
        } else {
            txtEmail.text = user?.email

        }
        txtCache.text = CacheManager.getTotalCacheSize(this)
        swImage.setOnCheckedChangeListener { _, isChecked ->
            SharePreferUtils.put(this, "showImage", isChecked)
        }
    }

    override fun initDatas() {
    }

    @OnClick(R.id.image_back, R.id.txt_exit, R.id.line_clear, R.id.line_pass)
    fun OnClick(view: View) {
        when (view.id) {
            R.id.image_back -> finish()
            R.id.txt_exit -> {
                SharePreferUtils.put(this, "user", "")
                openActivity(LoginActivity::class.java)
                finish()
            }
            R.id.line_clear -> {
                CacheManager.clearAllCache(applicationContext)
                txtCache.text = CacheManager.getTotalCacheSize(this)
            }
            R.id.line_pass -> showSetPass()

        }
    }

    fun showSetPass() {
        val view = LayoutInflater.from(this).inflate(R.layout.view_dialog_edit, null)
        val builder = AlertDialog.Builder(this)
                .setView(view)
                .create()
        val edit1 = view.findViewById<EditText>(R.id.edit_1)
        val edit2 = view.findViewById<EditText>(R.id.edit_2)

        val btn1 = view.findViewById<TextView>(R.id.txt_btn_1)
        btn1.setOnClickListener { if (builder.isShowing) builder.dismiss() }
        val btn2 = view.findViewById<TextView>(R.id.txt_btn_2)
        btn2.setOnClickListener {
            setPass(edit1.text.toString(), edit2.text.toString())
            user!!.sign = edit1.text.toString()
            if (builder.isShowing) builder.dismiss()
        }
        builder.show()

    }

    fun setPass(pass1: String, pass2: String) {
        if (StringUtil.isBlank(pass1) || StringUtil.isBlank(pass2)) {
            showToastShort("输入为空")
            return
        }
        if (pass1 != user!!.password) {
            showToastShort("原密码输入有误")
            return
        }
        val params = mapOf(Pair("token", Comm.TOKEN), Pair("password", pass2))
        val service = BaseRetrofit().createService(ServerApi::class.java)
        service.update(params)
                .subscribeOn(Schedulers.newThread())
                .subscribeOn(Schedulers.io())
                .subscribe({ reponse ->
                    when (reponse.getCode()) {
                        200 -> {
                            LogUtil.i(TAG,reponse.getData().toString())
                            user!!.password = pass2
                            SharePreferUtils.put(this,"user",GsonUtils.Gson2Str(reponse.getData()))
                            sendMsg("设置成功", 0x123, handler)
                        }
                        else -> sendMsg(reponse.getMessage(), 0x123, handler)
                    }
                }, { t ->
                    LogUtil.e(TAG, "异常：" + t.message)
                })
    }

    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0x123 -> {
                showToastShort(msg.data.getString("msg"))
            }
        }
        false
    })

    override fun onDestroy() {
        super.onDestroy()
    }
}